package com.bookstore.servlet;

import com.bookstore.pojo.User;
import com.bookstore.services.Impl.UserServiceImpl;
import com.bookstore.services.UserService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {
    UserService userService=  new UserServiceImpl();

    /**
     * 登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonUser = request.getParameter("jsonUser");
        Gson gson=new Gson();
        User user = gson.fromJson(jsonUser, User.class);
        List<User> users = userService.selectUsers();
        HttpSession session = request.getSession();
        for (User user1:users) {
            if(user1.getUsername().equals(user.getUsername())){
                if(user1.getPassword().equals(user.getPassword())){
                    System.out.println(user);
                    response.setStatus(200);
                    session.setAttribute("user",user1);
                }
                response.sendError(300);
                break;
            }
        }
        response.sendError(300);
    }

    /**
     * 注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonUser = request.getParameter("jsonUser");
        Gson gson=new Gson();
        User user = gson.fromJson(jsonUser, User.class);
        List<User> users = userService.selectUsers();
        String msg="";
        for (User user1:users) {
            if(user1.getUsername().equals(user.getUsername())){
                msg="用户已存在";
                request.setAttribute("msg",msg);
            }
        }
        userService.registUser(user);
        request.getRequestDispatcher("pages/user/login.html").forward(request,response);
    }
}
